跳到主要内容

3.1-语言特性

Create by fall on 17 Nov 2021 Recently revised in 26 Sep 2023

类型拓宽

如果指定了初始值,并且未显示添加类型注释,那么 TS 会对类型进行推断,推断的类型就是指定的字面量类型的拓宽类型。

// const 声明时 TypeScript 推断出它的类型直接由赋值字面量的类型决定
const str1 = 'this is string'; // 类型是 'this is string'
// let 声明时,回复语字面量类型的父类型
let str2 = 'any string';// 类型是 string
let strFun = (str='It is string')=>str
// 类型是(str?:string)=string
let str3 = str1 // 类型是 string

特殊字段的类型拓宽

let  x = null     // any
let y = undefined // any

const z = null // null

let x2 = x // null
let y2 = y // undefined
let z2 = z // null

类型拓宽引出的问题

interface Vector3 {
x: number;
y: number;
z: number;
}

function getComponent(vector: Vector3, axis: "x" | "y" | "z") {
return vector[axis];
}
let x = "x";
let vec = { x: 10, y: 20, z: 30 };
// 类型“string”的参数不能赋给类型“"x" | "y" | "z"”的参数。
// 因为需要传入的 x 的推断类型是 "x",此处的 x 类型为 string
getComponent(vec, x); // Error
// 解决方案,换为 const 声明 或者换为下面的声明方式
// let x:'x' = 'x'

比如说,声明一个

const arr = ['x', 1];
// 尽管 TS 很聪明,但可能的推断有很多种:
// ('x' | 1)[]
// ['x', 1]
// [string, number]
// readonly [string, number]
// (string | number)[]
// readonly (string|number)[]
// [any, any]
// any[]

所以,在类型宽拓中,出现问题,const 只能解决一类问题,遇到复杂的数组仍会有问题。

对象的声明

const obj = { 
x: 1,
oon:22 as const // 值空间引入符号,纯粹的类型级构造,将 oon 声明为一个类型为 22 的数字
};
obj.x = 6;
obj.x = '9';// error
// 因为声明后,会自动确定类型,x会被确定为 number 类型
obj.y = 8;// error
// 对象 obj 上不存在 y,name 所以不能修改其值
obj.name = 'semlinker';// error
obj.oon = 12
// onn的类型是 22 所以,无法改变其值

声明只读属性

const obj = {
name:'流星雨',
age:79
} as const
obj.age = 999 // error
// 此时声明的是只读属性
// 当然,也可以在数组中使用
const arr = ['PPAP','pineapple']

类型缩小

类型缩小实际上就是通过判断,typeof 或者是 as 进行类型断言